// 导入相关模块
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser');
const app = express()
const port = 3000
const fs = require('fs')


var write = function (url, data) {
	try {
		fs.writeFileSync(url, data);
		return null;
	} catch (error) {
		return error;
	}
}

// 配置
app.engine('html', require('express-art-template'));
app.use('/node_modules/', express.static(path.join(__dirname, './node_modules')));
app.use('/public/', express.static(path.join(__dirname, './public')));

// 处理post 请求
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// 路由
app.get('/', (req, res) => {
	// res.render('index.html');
	res.send('Welcome')
})

app.get('/information', (req, res) => {
	var folders = []
	fs.readdir('public', function(err,files){
	if (err){
		console.log(err);
	}
		folders = files;
	})
	res.send('good');
	
	
})

app.get('/write', (req, res) => {
	res.render('write.html');
})

app.post('/write', (req, res) => {
	var data = JSON.stringify(req.body);
	data = JSON.parse(data) 
	var title = data.title
	console.log(title);
	data = data.data;
	console.log(data);
	var html = `
		<!DOCTYPE html>
		<html>
			<head>
				<meta charset="utf-8" />
				<meta name="viewport" content="width=device-width, initial-scale=1">
				<link rel="stylesheet" type="text/css" href="/public/Css/article.css"/>
				<title>${title}</title>
			</head>
			<body>
				${data}
			</body>
		</html>
		`
	result = write('./public/'+title+'.html', html)
	if (result) {
		console.log(result);
	} else {
		res.send('success');	
	}
})


// 开启服务器
app.listen(port, () => console.log(`Example app listening on port ${port}!`))